<%@ page language="java" import="java.util.*" pageEncoding="utf8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">

    <title>MainPage</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">

    <link rel="stylesheet" type="text/css" href="http://94.191.105.89:8888/jlitetest/css/main.css">
    <script src="/jlitetest/js/LiteJS/Lite.js" type="text/javascript"></script>

</head>

<body>
<div>
    <h3>status:</h3>
    <p>
        <%
            String unm = (String) request.getAttribute("data");
            if (unm == null) {
                out.write("not login yet!");
            } else {
                out.write("Welcome " + unm + " home.");
            }
        %>
    </p>
</div>
<div>
    <h3>switch identity:</h3>
    <p>
        <a href="/jlitetest/charts/login.yx?unm=Sam&pwd=sam">LoginAsEmployee</a>
    </p>
    <p>
        <a href="/jlitetest/charts/login.yx?unm=Xavi&pwd=xavi">LoginAsManager</a>
    </p>
</div>

<div id="menu">
    department:
    <select id="sltDept">
        <option value="1">first</option>
        <option value="2">second</option>
    </select>
    <br>
    search item:
    <select id="sltItem">
        <option value="1">salary</option>
        <option value="2">profit</option>
    </select>
    <br>
    <button id="btn">OK</button>
</div>

<div id="container">
    <div>
<%--        <form action="/jlitetest/storage/delegate.yx">--%>
            <input type="text" id="remote_url" e-model="target_url"/>
            <input type="submit" id="submit">
<%--        </form>--%>
    </div>
    <div>
        <ul id="list"></ul>
    </div>
</div>
<script>
    document.getElementById("btn").onclick = function () {
        var dept_id = document.getElementById("sltDept").value;
        var item = document.getElementById("sltItem").value;
        if (item == 2) {
            window.location.href = "/jlitetest/charts/profitDept.yx?dept_id=" + dept_id;
        } else if (item == 1) {
            window.location.href = "/jlitetest/charts/salaryDept.yx?dept_id=" + dept_id;
        }
    };

    var liSegmentStr = "<li class='file_item'><span>??</span><button e-click='downloadNow' class='download'>------>下载</button></li>";
    elite.use(["http", "core", "move", "UI"], _run);

    var _target_url = "TODO";

    function _run() {
        var ema = new ECtrl({
            view: "#div01",
            data: {
                "target_url": _target_url
            },
            methods: {
                "downloadNow": function (elem, event) {
                    downLoadNow(elem.previousSibling.textContent.trim());
                }
            }
        });

        var totalItemSegmentStr = "";
        // 创建列表
        $http({
            url: "/jlitetest/storage/list.yx",
            method: "post",
            data: {
                createUser: "alex"
            },
            async: false,
            success: function (responseText) {
                var jsonArr = JSON.parse(responseText);
                for (var i in jsonArr) {
                    var singleLiSegmentStr = liSegmentStr.replace("??", jsonArr[i].fileName);
                    totalItemSegmentStr += singleLiSegmentStr;
                }
                // document.querySelector("#list").appendChild(createNewElement("li", totalItemSegmentStr));
                document.querySelector("#list").innerHTML = totalItemSegmentStr;
            },
            Error: function (err_msg) {
                console.error(err_msg);
            }
        });

        bindDownLoad();
        buildDelegate();

    }

    function bindDownLoad() {
        document.querySelectorAll(".download").forEach(function (elem, i) {
            elem.addEventListener("click", function () {
                downLoadNow(elem.previousSibling.textContent.trim());
            })
        });
    }

    function downLoadNow(fileName) {
        openWindow("/jlitetest/storage/download.yx?fileName=" + encodeURI(fileName) + "&createUser=alex", '_blank', fileName, true);
    }

    function buildDelegate(){
        document.querySelector("#submit").addEventListener("click", function(elem){
            var remote_url = document.querySelector("#remote_url").value;
            $http({
                url: "/jlitetest/storage/delegate.yx",
                method: "post",
                data: {
                    createUser: "alex",
                    remoteFilePath: remote_url
                },
                async: false,
                success: function (responseText) {
                    console.info(JSON.parse(responseText));
                },
                Error: function (err_msg) {
                    console.error(err_msg);
                }
            });
        })
    }

    /**
     * a模拟window.open，不会被浏览器拦截
     * @param {String} url        a标签打开的地址
     * @param {String} id         a标签的ID
     * @param {String} targetType a标签点击打开的方式（当前页面打开还是新窗口打开）
     */
    function openWindow(url, targetType, id, _download) {
        // targetType = '_blank', id = 'open', _download = false
        // 如果存在则删除
        if (document.getElementById(id)) {
            document.body.removeChild(document.getElementById(id))
        }
        var a = document.createElement('a');
        a.setAttribute('href', url);
        if (_download) {
            a.setAttribute('download', url);
        }
        a.setAttribute('target', targetType);
        a.setAttribute('id', id);
        document.body.appendChild(a);
        a.click()
    }

    function createNewElement(node_type, node_content) {
        var newNode = document.createElement(node_type);//创建一个div标签
        newNode.textContent(node_content);
        return newNode;
    }
</script>
</body>
</html>